<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\ApppageAreaRequest;
use App\Models\Application\Application;
use App\Models\Application\Apppage;
use App\Models\Application\ApppageArea;
use App\Models\Application\Bartpl;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Application\PaneltplType;
use App\Repositories\Application\ApppageAreaRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;

class ApppageAreaController extends Controller
{
    use ModelForm;

    /** @var  ApppageAreaRepository */
    private $apppageAreaRepository;

    public function __construct(ApppageAreaRepository $apppageAreaRepo)
    {
        $this->apppageAreaRepository = $apppageAreaRepo;
    }

    /**
     * Display a listing of the ApppageArea.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $appPageId     = $request->input('apppage_id');
        $applicationId = $request->input('application_id');
        if (!empty($appPageId) && !empty($applicationId)) {
            $apppage = Apppage::find($appPageId);

            if (empty($apppage)) {
                Flash::error(__('application.apppages.not_found'));
                return redirect(route('application.apppages.index'));
            }
            // 获取栏目推荐区位信息定义
            $pagetplAreas = ApppageArea::where(['apppage_id' => $appPageId, 'application_id' => $applicationId])->get();
            if (empty($pagetplAreas->first())) {
                // 获取panel模板信息
                $pagetpl          = Pagetpl::with(['pagetplAreas'])->where(['id' => $apppage->pagetpl_id])->first();
                $apppageAreaDatas = [];
                $areas            = json_decode($pagetpl->layout, true);
                if (!empty($areas)) {
                    foreach ($areas as $key => $area) {
                        $apppageAreaDatas[$key]['application_id']    = intval($applicationId);
                        $apppageAreaDatas[$key]['apppage_id']        = intval($appPageId);
                        $apppageAreaDatas[$key]['pagetpl_id']        = intval($apppage->pagetpl_id);
                        $apppageAreaDatas[$key]['area']              = $area;
                        $apppageAreaDatas[$key]['panteltpl_type_id'] = 0;
                        $apppageAreaDatas[$key]['tpl_id']            = null;
                        $apppageAreaDatas[$key]['inner']             = null;
                        $apppageAreaDatas[$key]['onup']              = null;
                        $apppageAreaDatas[$key]['ondown']            = null;
                        $apppageAreaDatas[$key]['onleft']            = null;
                        $apppageAreaDatas[$key]['onright']           = null;
                        $apppageAreaDatas[$key]['options']           = null;
                        $apppageAreaDatas[$key]['description']       = null;
                        $apppageAreaDatas[$key]['created_at']        = date('Y-m-d H:i:s', time());
                    }
                }
                $result = DB::table('apppage_areas')->insert($apppageAreaDatas);
                if (empty($result)) {
                    Flash::error(__('application.pagetpls.not_found'));

                    return redirect(route('application.pagetpls.index'));
                }
            }
        }
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('application.apppage_areas.index_header'));
            $content->description(__('application.apppage_areas.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new ApppageArea.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.apppage_areas.create_header'));
            $content->description(__('application.apppage_areas.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created ApppageArea in storage.
     *
     * @param ApppageAreaRequest $request
     *
     * @return Response
     */
    public function store(ApppageAreaRequest $request)
    {
        $input = $request->all();

        $apppageArea = $this->apppageAreaRepository->create($input);

        Flash::success(__('application.apppage_areas.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.apppage_areas.index'));

    }

    /**
     * Display the specified ApppageArea.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $apppageArea = $this->apppageAreaRepository->findWithoutFail($id);

        if (empty($apppageArea)) {
            Flash::error(__('application.apppage_areas.not_found'));

            return redirect(route('application.apppage_areas.index'));
        }

        return view('application.apppage_areas.show')->with('apppageArea', $apppageArea);

    }

    /**
     * Show the form for editing the specified ApppageArea.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $apppageArea = $this->apppageAreaRepository->findWithoutFail($id);

        if (empty($apppageArea)) {
            Flash::error(__('application.apppage_areas.not_found'));

            return redirect(route('application.apppage_areas.index'));
        }
        // 执行编辑参数函数
        Admin::script('editApppageAreaArea(' . $id . ');');
        $pagetpls                 = Pagetpl::pluck('title', 'id');
        $applications             = Application::pluck('title', 'id');
        $paneltplTypes            = PaneltplType::pluck('title', 'id');
        $apppages                 = Apppage::pluck('title', 'id');
        $data['pagetpls']         = $pagetpls;
        $data['paneltplTypes']    = $paneltplTypes;
        $data['applications']     = $applications;
        $data['apppages']         = $apppages;
        $data['pagetplArea']      = $apppageArea->toArray();
        $data['edit_header']      = __('application.pagetpl_areas.edit_header');
        $data['edit_description'] = __('application.pagetpl_areas.edit_description');
        return view('application.apppage-areas.edit', $data);

        // return Admin::content(function (Content $content) use ($id) {

        //     $content->header(__('application.apppage_areas.edit_header'));
        //     $content->description(__('application.apppage_areas.edit_description'));

        //     $content->body($this->form()->edit($id));
        // });
    }

    /**
     * Update the specified ApppageArea in storage.
     *
     * @param  int              $id
     * @param ApppageAreaRequest $request
     *
     * @return Response
     */
    public function update($id, ApppageAreaRequest $request)
    {
        $apppageArea = $this->apppageAreaRepository->findWithoutFail($id);

        if (empty($apppageArea)) {
            Flash::error(__('application.apppage_areas.not_found'));

            return redirect(route('application.apppage_areas.index'));
        }
        $input = $request->all();
        $apppageArea = $this->apppageAreaRepository->update($input, $id);

        $url         = route('application.apppage_areas.index');
        return response()->json(['content' => '修改成功!', 'status' => true, 'url' => $url]);
        // Flash::success(__('application.apppage_areas.updated_success'));

        // return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.apppage_areas.index'));
    }

    /**
     * Remove the specified ApppageArea from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->apppageAreaRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.apppage_areas.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $apppageArea = $this->apppageAreaRepository->findWithoutFail($id);

        if (empty($apppageArea)) {
            Flash::error(__('application.apppage_areas.not_found'));

            return redirect(route('application.apppage_areas.index'));
        }

        if ($flag = $this->apppageAreaRepository->delete($id)) {

            return response()->json(['message' => __('application.apppage_areas.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ApppageArea::class, function (Form $form) {

            $form->display('id', 'ID');
            $applications = Application::pluck('name', 'id');
            $form->select('application_id', '应用')->options($applications);
            $apppages = Apppage::pluck('title', 'id');
            $form->select('apppage_id', '应用页面名称')->options($apppages);
            $pagetpls = Pagetpl::pluck('title', 'id');
            $form->select('pagetpl_id', 'page模板名称')->options($pagetpls);
            $form->text('area', '区位编号');
            $paneltplTypes = PaneltplType::pluck('name', 'id');
            $form->select('panteltpl_type_id', '模板类型')->options($paneltplTypes)->load('tpl_id', route('application.apppage_areas.paneltpl_types'), 'id', 'title');
            $paneltpls = Paneltpl::pluck('title', 'id');
            $form->select('tpl_id', '模板名称')->options($paneltpls);
            $form->text('inner', 'inner');
            $form->text('onup', 'onup');
            $form->text('ondown', 'ondown');
            $form->text('onleft', 'onleft');
            $form->text('onright', 'onright');
            $form->text('options', 'options');
            $form->textarea('description', '说明');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(ApppageArea::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            if (!empty($appPageId = $request->get('apppage_id'))) {
                $grid->model()->where(['apppage_id' => $appPageId]);
            } else {
                $grid->model();

            }
            // // 添加按钮
            // if (!\Gate::check('application.apppage_areas.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.apppage_areas.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.apppage_areas.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.apppage_areas.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            $grid->tools(function ($tools) {
                // $tools->batch(function ($batch) {
                //     // 批量删除按钮
                //     if (!\Gate::check('application.apppage_areas.batch_destroy')) {
                //         $batch->disableDelete();
                //     }
                // });
                $tools->append('<a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default btn-sm" style="margin-right: 0px"> <i class="fa fa-arrow-left"></i>返回</a>');
            });

            // 添加按钮
            if (Admin::user()->cannot('application.apppage_areas.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('application.apppage_areas.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.apppage_areas.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.apppage_areas.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.apppage_areas.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('application.name', '应用')->sortable();
            $grid->column('apppage.title', '应用页面名称')->sortable();
            $grid->column('pagetpl.title', 'page模板名称')->sortable();
            $grid->column('area', '区位编号')->sortable();
            $grid->column('paneltplType.name', '模板类型')->sortable();
            $grid->column('tpl_id', '模板名称')->display(function ($val) {
                $name             = '';
                $paneltplTypeName = PaneltplType::where(['id' => $this->paneltpl_type_id])->value('name');
                switch ($paneltplTypeName) {
                    case 'barTpl':
                        $name = Bartpl::where(['id' => $val])->value('title');
                        break;
                    case 'panelTpl':
                        $name = Paneltpl::where(['id' => $val])->value('title');
                        break;
                    default:
                        # code...
                        break;
                }
                return $name;
            });
            $grid->column('inner', 'inner')->sortable();
            $grid->column('onup', 'onup')->sortable();
            $grid->column('ondown', 'ondown')->sortable();
            $grid->column('onleft', 'onleft')->sortable();
            $grid->column('onright', 'onright')->sortable();
            $grid->column('options', 'options')->sortable();
            $grid->column('description', '说明')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /* 根据模板类型获取不同的模板数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getTpldataByTpltype(Request $request)
    {
        $paneltplId = $request->get('q');
        $returnData = [];

        $data = PaneltplType::where(['id' => $paneltplId])->first();
        if (!empty($data)) {
            $dataName = $data->name;
            //  如果推荐模板类型为0, 则获取模板相关数据
            if ($dataName === 'barTpl') {
                $returnData = Bartpl::get(['title', 'id'])->toArray();
                // 如果推荐模板类型为1, 则获取栏目列表数据
            } elseif ($dataName === 'widget') {
                // $returnData = Muticolumn::orderBy('listorder', 'asc')->get(['name', 'id'])->toArray();
            } elseif ($dataName === 'panelTpl') {
                $returnData = Paneltpl::get(['title', 'id'])->toArray();
            }
        }
        return $returnData;
        // return array_merge([['id' => '', 'name' => '选择']], $retunData);
    }
}
